import {
  indexApi
} from '../../../api/index';
import {
  request
} from '../../../utils/request';
import {
  areaList
} from '@vant/area-data';

import Toast from '@vant/weapp/toast/toast';
Page({
  data: {
    defaultData: {
      title: "添加收货地址", // 导航栏标题
      imageSrc: "/images/back.png",
      isBackToPreviousPage: true
    },
    checked: false, //默认地址复选框
    is_default: 0,
    recipientName: null, //收件人名字
    phoneNumber: null, //手机号
    detaileAddress: null, //详细地址
    area: null,
    city: null,
    province: null,
    errorMessage: '', //手机号输入错误
    addressPop: false,
    areaList, //地址列表
    selectedAddress: null, //用户选择的地址
    addressId: "",
    fromPage:null
  },

  onLoad(options) {
    if (options.address) {
      const address = JSON.parse(decodeURIComponent(options.address));
      const {
        province,
        area,
        city,
        detail,
        nickName,
        phone,
        addressId
      } = address
      const selectedAddress = province + " " + area + " " + city
      this.setData({
        province,
        area,
        city,
        addressId,
        selectedAddress,
        detaileAddress: detail,
        recipientName: nickName,
        phoneNumber: phone
      });
    }

    if (options.fromPage) {
      this.setData({
        fromPage: options.fromPage
      });
      console.log("options.fromPage",this.data.fromPage);
    }
  },

  //默认地址
  onChange(event) {
    this.setData({
      checked: event.detail,
    });
    console.log("checked", this.data.checked);
    const is_default = this.data.checked ? 0 : 1;
    this.setData({
      is_default: is_default,
    });
  },

  //收件人
  RecipientChange(event) {
    this.setData({
      recipientName: event.detail,
    });
    console.log("recipientName", this.data.recipientName);
  },

  // 手机号
  PhoneNumberChange(event) {
    const phoneRegex = /^1[3-9]\d{9}$/;
    if (!phoneRegex.test(event.detail)) {
      this.setData({
        errorMessage: '请输入有效的中国大陆手机号码'
      });
    } else {
      this.setData({
        phoneNumber: event.detail,
        errorMessage: ''
      });
    }
    console.log("phoneNumber", this.data.phoneNumber);
  },

  // 详细地址
  detaileAddressChange(event) {
    this.setData({
      detaileAddress: event.detail,
    });
    console.log("detaileAddress", this.data.detaileAddress);
  },


  // 弹框
  clickIcon() {
    console.log("ddddd");
    this.setData({
      addressPop: true
    })
  },

  onClose() {
    this.setData({
      addressPop: false
    });
  },
  cancelPop() {
    this.setData({
      addressPop: false
    });
  },
  //选择地址
  confirmPop(event) {
    const selectedValues = event.detail.values;
    console.log('用户选择的省市区信息：', selectedValues);
    const selectedAddress = selectedValues.map(item => item.name).join(' ');
    const [province, city, area] = selectedValues.map(item => item.name);
    console.log("area", area);
    this.setData({
      selectedAddress,
      addressPop: false,
      province,
      city,
      area
    });
    console.log("selectedAddress", this.data.selectedAddress);
  },

  //保存，新增地址
  async addAddress() {
    const {
      recipientName,
      phoneNumber,
      selectedAddress,
      detaileAddress,
      addressId
    } = this.data;
    // 校验表单
    if (!recipientName) {
      Toast('请输入收件人名字');
      return;
    }
    if (!phoneNumber) {
      Toast('请输入手机号');
      return;
    }
    if (!selectedAddress) {
      Toast('请选择所在地区');
      return;
    }
    if (!detaileAddress) {
      Toast('请输入详细地址');
      return;
    }

    try {
      const res = await request({
        url: indexApi.addAddressApi(),
        method: "POST",
        data: {
          addressId: this.data.addressId,
          province: this.data.province,
          city: this.data.city,
          area: this.data.area,
          detail: this.data.detaileAddress,
          is_default: this.data.is_default,
          nickName: this.data.recipientName,
          phone: this.data.phoneNumber,
          // userId: 0
        }
      });
      if (res.code == 200 && addressId == "") {
        console.log("addressId", addressId);
        wx.showToast({
          title: "添加成功",
          icon: "none",
        });
      }
      if (res.code == 200 && addressId !== "") {
        console.log("addressId", addressId);
        wx.showToast({
          title: "修改成功",
          icon: "none",
        });
      }
      console.log("res", res);

      setTimeout(() => {
        wx.navigateBack();
      }, 1000);
  } catch (error) {
      console.error("Error:", error);
    }
  },

  toBack() {
    wx.navigateBack({
      delta: 1
    });
  }
})